function BondMarket_DataManager(){
	this.cache={};
}

BondMarket_DataManager.prototype={
	TreasuryYieldsUrl:"../invoke/getTreasuryYields",
	GovtBondUrl:"../invoke/getUSGovtBond",
	
	TreasuryChartDataUrl:"../invoke/treaBondHis?range=",
	USGOVChartDataUrl:"../invoke/govBondHis?govtBondType=",
	loadTreasuryData:function(callback){
//		var data = {};
        $.get(this.TreasuryYieldsUrl,function(data){
			callback($.evalJSON(data));
		});
	},
	
	loadUSGovtData:function(callback){
//		var data = {};
        $.get(this.GovtBondUrl,function(data){
			callback($.evalJSON(data));
		});
	},
	/*
	{	1, "1 Month";
		2, "3 Month";
		3, "6 Month";
		4, "1 Year";
		5, "2 Year";
		6, "3 Year";
		7, "5 Year";
		8, "7 Year";
		9, "10 Year";
		10, "20 Year";
		11, "30 Year";
	}
	{
		1:"US%20Govt%20Bond",
		2:"Short-Term%20US%20Govt%20Bond",
		3:"Intermediate%20US%20Govt%20Bond",
		4:"Long-Term%20US%20Govt%20Bond"
	}
	*/
	paramMap:{'1YEAR':4,
	'2YEAR':5,
	'3YEAR':6,
	'5YEAR':7,
	'10YEAR':9,
	
	'usgov':1,
	'shortusgov':2,
	'midusgov':3,
	'longusgov':4
	},
	loadUSGovtChartData:function(param,callback){
		if(this.cache[param]){
			callback(this.cache[param]);
			return;
		}
		var self=this;
		$.get(this.USGOVChartDataUrl+this.paramMap[param],function(data){
			var jData=$.evalJSON(data);
			if(jData.errorCode!=200) return;
			callback(jData);
			self.cache[param]=jData;
		});
	},
	loadTreasuryChartData:function(param,callback){
		if(this.cache[param]){
			callback(this.cache[param]);
			return;
		}
		var self=this;
		$.get(this.TreasuryChartDataUrl+this.paramMap[param],function(data){
			var jData=$.evalJSON(data);
			if(jData.errorCode!=200) return;
			callback(jData);
			self.cache[param]=jData;
		});
	}
}


var gBondMarket_DataManager=new BondMarket_DataManager();


function QS_MarketBond(container,cfg,callbacks){
	var self=this;
	this.$container=(typeof container)=="string" ? $("#"+container) : container;
    this.callbacks = callbacks||{};
	this.cfg={
		w:this.$container.width()||400,
		h:this.$container.height()||300,
		defaultMenuId:0,
		lineColor:"#054fbd",
		fillColor:"#aac1e2"
	}
	$.extend(true,this.cfg,cfg);
	this.$container.css({width:this.cfg.w,height:this.cfg.h});
	
	if(QS_Lang.marketBond){
		this.init();
	}else{
		$.getScript("../js/language/en_us/qs_marketbond_en_us.js", function(){
			self.init();
		});
	}
}

QS_MarketBond.prototype={
	init:function(){
		var self=this;
		//init dom
		var lang = this.lang = QS_Lang.marketBond;

		this.$container.append('<div class="bondmarket">'+
									'<div class="bm-tabmenuwrap">'+
										'<div class="bm-tabmenu"></div>'+
									'</div>'+
								'</div>');
								
		//init menu
		var tabData = [ {txt: lang['treasuryyield'],id: 1,closable: false}, 
						{txt: lang['usgovbond'],id: 2,closable: false}, 
						{txt: '10 '+lang['years']+' '+lang['tnoteyield'],id: 3,closable: false}];
						
		this.$tabMenu=this.$container.find(".bm-tabmenu");
		var tabMenu = new Util.TabMenu(this.$tabMenu[0], tabData, {
			onActive:function(tab){
				if(tab.index==0){
					self.bmChart1 && self.bmChart1.changeOutSize(self.imgW, self.imgH);
				}else if(tab.index==1){
//					self._loadChartData(tab.index,0);
					self.bmChart2.changeOutSize(self.imgW, self.imgH);
				}else if(tab.index==2){
//					self._loadChartData(tab.index,0);
					self.bmChart3.changeOutSize(self.imgW, self.imgH);
				}
			}
		}, {
//			width: 80,
//			tabsList: false,
//			rearrange: true,
			needTitle:true
		});
		var contentData=[{
			gridHead:{rowName:lang['maturity'], valName:lang['pyield']},
			gridData:[	{name:'6 '+lang['month'],val:""},
						{name:'2 '+lang['years'],val:""},
						{name:'5 '+lang['years'],val:""},
						{name:'10 '+lang['years'],val:""},
						{name:'30 '+lang['years'],val:""}],
			chartHead:{left:lang['oneyearago'],right:lang['lastclose']},
			footerText:lang['dataasoflastclose']
		},{
			gridHead:{rowName:lang['msindex'], valName:lang['value']},
			gridData:[	{name:lang['usgov'],val:""},
						{name:lang['shortusgov'],val:""},
						{name:lang['midusgov'],val:""},
						{name:lang['longusgov'],val:""}],
			chartHead:{left:lang['usgovbond']},
			footerText:lang['dataasoflastclose']
		},{
			gridHead:{rowName:lang['maturity'], valName:lang['pyield']},
			gridData:[	{name:'1 '+lang['year'],val:""},
						{name:'2 '+lang['years'],val:""},
						{name:'3 '+lang['years'],val:""},
						{name:'5 '+lang['years'],val:""},
						{name:'10 '+lang['years'],val:""}],
			chartHead:{left:this._getTitle(2,0)},
//			imageSrc:"http://tools.morningstar.com/new_home_page/home_page_image.aspx?type=BC_30YEAR",
			footerText:lang['dataasoflastclose']
		}];
		
		contentTemplate='<div class="bm-content-wrap">'+
							'<div class="bm-content-grid-wrap">'+
								'{{#gridHead}}'+
									'<div class="bm-gridhead-row"><span>{{rowName}}</span><span>{{valName}}</span></div>'+
								'{{/gridHead}}'+
								'<div class="bm-gridbody">'+
									'{{#gridData}}'+
										'<div class="bm-grid-row"><span>{{name}}</span><span class="bm-grid-value">{{val}}</span></div>'+	
									'{{/gridData}}'+
								'</div>'+
							'</div>'+
							'<div class="bm-content-chart-wrap">'+
								'<div class="bm-chart-title-wrap">'+
									'<span>{{chartHead.left}}</span><span>{{chartHead.right}}</span>'+
								'</div>'+
								'<div class="bm-chart-main-wrap">'+
//									'{{#imageSrc}}'+
//										'<img src="{{imageSrc}}"/>'+
//									'{{/imageSrc}}'+
								'</div>'+
							'</div>'+
							'<div class="bm-content-footer">{{footerText}}</div>'+
						'</div>';
		
		
		
		for(var i=0;i<tabMenu.tabs.length;i++){
			tabMenu.tabs[i].panel.append(Mustache.render(contentTemplate,contentData[i]));
		}
		
		this.$contentWrap = this.$container.find('.bm-content-wrap');
		this.$contentGridWrap = this.$contentWrap.find('.bm-content-grid-wrap');
		this.$contentChartWrap = this.$contentWrap.find('.bm-content-chart-wrap');
			
		this.$chartTitleWrap = this.$contentChartWrap.find('.bm-chart-title-wrap');
		var $tab1Title=this.$chartTitleWrap.first().find('span');
		$tab1Title.eq(0).addClass('bm-charthead-year');
		$tab1Title.eq(1).addClass('bm-charthead-close');
		
		this.chartTitleH=this.$chartTitleWrap.height();
		this.footerH = this.$contentWrap.find('.bm-content-footer').outerHeight(true);
		
		this.$imgsCtn = this.$contentChartWrap.find('.bm-chart-main-wrap');
		//fix second img text
//		this.$fixOneMonth=$('<div class="bm-fix-onemonth">'+lang['onemonth']+'</div>').appendTo(this.$imgsCtn.eq(1));
		
//		this.$imgs = this.$imgsCtn.find("img");
		
		this.$gridBody = this.$contentGridWrap.find('.bm-gridbody');
		this.$gridBody.eq(1).addClass('bm-grid-hover');
		this.$gridBody.eq(2).addClass('bm-grid-hover');
		
		this._bindEvent();
		
		this.bmChart1 = new MarketBondLineChart(this.$imgsCtn.eq(0),{tabIndex:0});
		this.bmChart2 = new MarketBondLineChart(this.$imgsCtn.eq(1),{tabIndex:1,dist:{left:0}});
		this.bmChart3 = new MarketBondLineChart(this.$imgsCtn.eq(2),{dist:{left:0}});

		this.loadData();
		this.changeOutSize(this.cfg.w, this.cfg.h);
	},
	loadData:function(){
		var self = this;
		gBondMarket_DataManager.loadTreasuryData(function(jData){  // load the data of first tab
			jData&&self._updateData(jData);	
			 if(self.callbacks&&typeof(self.callbacks.onLoad)=="function"){
				self.callbacks.onLoad({});
			 }
		});
		
		gBondMarket_DataManager.loadUSGovtData(function(jData){
			jData&&self._updateData(jData);
		});
		
		this._loadChartData(1,0);
		this._loadChartData(2,0);
	},
	_getChartPoint:function(tData,a){
		var temp=[];
		for(var i in tData){
			var ticker=tData[i].ticker;
			for(var j in a){
				if(ticker==a[j]){
					temp.push(tData[i]);
					break;
				}
			}
		}
		return temp;
	},
	_updateData:function(jData){
		var lang=this.lang;
		if(jData.treasurys && jData.treasurys.length){
			var tData=jData.treasurys;
			for(var i in tData){
				var t=tData[i];
				if(typeof t.ClosePrice1Day !='undefined'){
					t.fixedPrice=parseFloat(t.ClosePrice1Day).toFixed(2);//fix float number
				}
			}
			
			var meta=this.metaMap().meta;
			var chart=this._getChartPoint(tData,meta.chart);
			var tab0=this._getChartPoint(tData,meta.tab0);
			var tab2=this._getChartPoint(tData,meta.tab2);

			var chartData=this.convertData(chart);
			chartData.lines[0].lineOption={lineType:"linePoint",lineColor:'#1B2064'};
			chartData.lines[1].lineOption={lineType:"linePoint",lineColor:'#F19620'};
			

			this.bmChart1.init(chartData);
//			tData.shift();//del 3 month
			this.bmChart1.changeOutSize(this.imgW, this.imgH);
			
			this.updataGridValue(0,tab0);
			this.updataGridValue(2,tab2);
			
		}else if(jData.bonds && jData.bonds.length){
			var bData=jData.bonds;
			for(var i in bData){
				if(typeof bData[i].LastPrice !='undefined'){
					bData[i].fixedPrice=parseFloat(bData[i].LastPrice).toFixed(2);
				}
			}

			this.updataGridValue(1,bData);
		}
	},
	updataGridValue:function(tabIndex, data){
		var $cells=this.$gridBody.eq(tabIndex).find('.bm-grid-row .bm-grid-value');
		$cells.each(function(i){
			var val=data[i].fixedPrice;
			if(typeof val !='undefined'){
				if(QS_NumFmt){
					val=QS_NumFmt.Fmt2(val,false,'',2);
				}
				$(this).html(val);
			}
		});
	},
	convertData:function(treasurys){
		var chartData={lines:[],xTick:[]};
		var lines = chartData.lines;
		var xTick = chartData.xTick;
		var lineD={data:[]};
		var lineY={data:[]};
		for(var i=0;i<treasurys.length;i++){
			var t=treasurys[i];
			if(typeof t.ClosePrice1Day !='undefined'){
				lineD.data[i]=t.fixedPrice;//parseFloat(t.ClosePrice1Day);
			}
			if(typeof t.ClosePrice1Year !='undefined'){
				lineY.data[i]=parseFloat(t.ClosePrice1Year);
			}
			t.ticker&&xTick.push(parseInt(t.ticker));
		}
		lines[0]=lineD;
		lines[1]=lineY;
		return chartData;
	},
	changeOutSize:function(w,h){
		var self=this;
		w=Math.max(w,380);
		h=Math.max(h,200);
		this.cfg.w = w;
		this.cfg.h = h;
		this.$container.css({width:w,height:h});
		var contentH = h - 28;
		var contentW = w;
		this.$contentWrap.css({width:contentW, height:contentH});
		
		this.$contentGridWrap.css({height:contentH-this.footerH});
		this.$contentChartWrap.css({height:contentH-this.footerH});

		this.imgW = contentW*0.64;
		this.imgH = contentH-this.footerH - this.chartTitleH;

		this.bmChart1.changeOutSize(this.imgW, this.imgH);
		this.bmChart2.changeOutSize(this.imgW, this.imgH);
		this.bmChart3.changeOutSize(this.imgW, this.imgH);
	},
	_getMetaData:function(tabIndex){
		if(tabIndex==1){
			return this.metaMap().bonds;
		}else if(tabIndex==2){
			return this.metaMap().treasurys;
		}
	},
	_getTitle:function(tabIndex,rowIndex){
		return this._getMetaData(tabIndex).chartTitle[rowIndex];
	},
	_getParam:function(tabIndex,rowIndex){
		return this._getMetaData(tabIndex).param[rowIndex];
	},
	_loadChartData:function(tabIndex, rowIndex){
		var self=this;
		var param=this._getParam(tabIndex, rowIndex);
		if(tabIndex==1){
			gBondMarket_DataManager.loadUSGovtChartData(param,function(jData){
				for(var i=0;i<jData.data.length;i++){
					jData.data[i]=parseFloat(jData.data[i]);
				}
				var chartData={
					lines:[{
						lineOption:{lineType:"mountain",lineColor:self.cfg.lineColor,fillColor:self.cfg.fillColor},
						data:jData.data//[1,1,3,5,6,6]
					}]
				};

				self.bmChart2.init(chartData);
				self.bmChart2.changeOutSize(self.imgW, self.imgH);
			});
		}else if(tabIndex==2){
			gBondMarket_DataManager.loadTreasuryChartData(param,function(jData){
				for(var i=0;i<jData.data.length;i++){
					jData.data[i]=parseFloat(jData.data[i]);
				}
				var chartData={
					lines:[{
						lineOption:{lineType:"mountain",lineColor:self.cfg.lineColor,fillColor:self.cfg.fillColor},
						data:jData.data//[1,1,3,5,6,6]
					}]
				};

				self.bmChart3.init(chartData);
				self.bmChart3.changeOutSize(self.imgW, self.imgH);
			});
		}
	},
	_bindEvent:function(){
		var self=this;
		this.$gridBody.not(this.$gridBody.first()).find('.bm-grid-row').unbind().bind('mouseenter',function(e){
//			if(e.target.tagName != "SPAN")return;
			var $row=$(this);
			var $grid=$row.parent();
			var tabIndex=self.$gridBody.index($grid);
			var rowIndex=$grid.find(".bm-grid-row").index($row);
			
			self._loadChartData(tabIndex,rowIndex);
			self.$chartTitleWrap.eq(tabIndex).find('span:first').html(self._getTitle(tabIndex,rowIndex));
		});
	},
	metaMap:function(){
		var self=this;
		return {
			bonds:{
				param:['usgov','shortusgov','midusgov','longusgov'],
				chartTitle:[self.lang['usgov'],self.lang['shortusgov'],self.lang['midusgov'],self.lang['longusgov']]
			},
			treasurys:{
				param:['1YEAR','2YEAR','3YEAR','5YEAR','10YEAR'],
				chartTitle:['1 '+self.lang['year']+' '+self.lang['noteyield'],'2 '+self.lang['years']+' '+self.lang['noteyield'],'3 '+self.lang['years']+' '+self.lang['noteyield'],'5 '+self.lang['years']+' '+self.lang['noteyield'],'10 '+self.lang['years']+' '+self.lang['noteyield']]
			},
			meta:{
				chart:["3 Month","6 Month","2 Year","5 Year","10 Year","30 Year"],
				tab0:["6 Month","2 Year","5 Year","10 Year","30 Year"],
				tab2:["1 Year","2 Year","3 Year","5 Year","10 Year"]
			}
		}
	},
	clear:function(){
		for(var p in this){
			if(!p || p == 'clear'){continue;}
			this[p] = null;
			delete this[p];
		}
	}
}


function QS_MarketBondTerminal(container,cfg){
	cfg.width&&(cfg.w=cfg.width);
	cfg.height&&(cfg.h=cfg.height);
	if(QS_Style){
		cfg.lineColor=QS_Style.chart.fillColors.minichartPchart || QS_Style.chart.fillColors.pChart || "#8ab9f3";
		cfg.fillColor=mstar.flotUtil.colorToRGB(cfg.lineColor,0.3);
	}

	this.obj=new QS_MarketBond(container,cfg);
}
QS_MarketBondTerminal.prototype={
	changeOutSize:function(w,h){
		this.obj.changeOutSize(w,h);
	},
	clear:function(){
		this.obj.clear();
	},
	saveConfig:function(){
		
	}
}
